//
//  UITextView-extension.swift
//  表情键盘的搭建
//
//  Created by 简康达 on 16/6/21.
//  Copyright © 2016年 JKD. All rights reserved.
//

import UIKit
extension UITextView{
    func getEmoticonString() -> String {
        //    用现在的内容创建一个可变属性字符串
        let attrMStr = NSMutableAttributedString(attributedString:attributedText)
        //        获取遍历的范围
        let rang = NSRange(location: 0, length: attrMStr.length)
        attrMStr.enumerateAttributesInRange(rang, options: []) { (dict, rang, _) in
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment where attachment.chs != nil {
                attrMStr.replaceCharactersInRange(rang, withString:attachment.chs!)
            }
        }
        return attrMStr.string
    }
    func insertEmoticon(emoticon:Emoticon) {
        //        判断是否是空表情
        if emoticon.isEmpty {
            return
        }
        //        判断是否是删除按钮
        if emoticon.isRemove {
            deleteBackward()
            return
        }
        //        判断是否是emoji表情
        if emoticon.emoji != nil {
            //            1.获取光标的位置
            let rang = selectedTextRange!
            //            2.将光标的位置替换成emoji表情
            replaceRange(rang, withText: emoticon.emoji!)
            return
        }
        //        普通表情
        //      1.创建属性字符串
        let tempFont = font!
        let attachment = EmoticonAttachment()
        attachment.chs = emoticon.chs
        attachment.image = UIImage(contentsOfFile: emoticon.pngPath!)
        attachment.bounds = CGRect(x: 0, y: -3, width: tempFont.lineHeight, height: tempFont.lineHeight)
        let imageAttrStr = NSAttributedString(attachment: attachment)
        //       2.获取光标的位置
        let rang = selectedRange
        //        3.根据原有的文字创建可变的属性字符串
        let attrMStr = NSMutableAttributedString(attributedString: attributedText)
        attrMStr.replaceCharactersInRange(rang, withAttributedString: imageAttrStr)
        attributedText = attrMStr
        //        4.重置光标
        selectedRange = NSRange(location: rang.location+1, length: 0)
        //        5.重置字体大小
        font = tempFont
    

    }
}
